package br.pucrio.inf.les.SPLAnalyser.impl.squidplugin.query.metricas;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;

import br.ufrn.dimap.ase.squid.core.models.squidmodel.Asset;
import br.ufrn.dimap.ase.squid.core.models.squidmodel.Class;
import br.ufrn.dimap.ase.squid.core.models.squidmodel.CodePiece;
import br.ufrn.dimap.ase.squid.core.models.squidmodel.Field;
import br.ufrn.dimap.ase.squid.core.models.squidmodel.Method;


public class CSVFile {
	private File csvFile;
	private String separator = ";";
	private String[] labels = { "TYPE", "NAME", "PATH", "OPERATION"};
	private List<String> ignoredOperations;
	
	public CSVFile(File file) {
		
		this.csvFile = file;
		this.ignoredOperations = new ArrayList<String>();
	}
	
	public CSVFile(File file, String[] ignoredOperations) {		
		this.csvFile = file;
		this.ignoredOperations = (List<String>) Arrays.asList(ignoredOperations);
	}
	
	public List<Artifact> read() {
		ArrayList<Artifact> assets = new ArrayList<Artifact>();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(csvFile));
			String line = null;
			
			while((line = reader.readLine()) != null) {
				HashMap<String, String> hash = new HashMap<String, String>();
				StringTokenizer st = new StringTokenizer(line, separator);
				for (String label : labels) {
					hash.put(label, st.nextToken());
				}
				if(!ignoredOperations.contains(hash.get("OPERATION"))) {
					assets.add(new Artifact(hash.get("TYPE"), hash.get("NAME"), hash.get("PATH"), hash.get("OPERATION")));
				}
			}
			
			return assets;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public void write(List<Asset> assets) {
		try {
			BufferedWriter br = new BufferedWriter(new FileWriter(csvFile));
			for (Asset asset : assets) {
				String type = "";
				if(asset instanceof Class) type = "CLASS";
				else if(asset instanceof Method) type = "METHOD";
				else if(asset instanceof Field) type = "FIELD";
				else if(asset instanceof CodePiece) type = "CODE PIECE";
				br.write(type+","+asset.getName()+","+asset.getPath()+", NULL\n");
			}
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
